package com.nari.ysphd.ui;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.intel.webrtc.base.ActionCallback;
import com.intel.webrtc.base.WoogeenException;
import com.jeremyfeinstein.conference.YCHSConferenceClient;
import com.jeremyfeinstein.event.RefreshEvent;
import com.jeremyfeinstein.event.SendMessageEvent;
import com.jeremyfeinstein.gson.Meeting;
import com.jeremyfeinstein.gson.OnResponse;
import com.jeremyfeinstein.okhttputil.callback.StringCallback;
import com.jeremyfeinstein.utils.AppConstants;
import com.jeremyfeinstein.utils.Comm;
import com.jeremyfeinstein.utils.ConfigUtil;
import com.jeremyfeinstein.utils.ToastUtil;
import com.jeremyfeinstein.utils.YCHSInstance;
import com.jeremyfeinstein.utils.YCHShttpAPI;
import com.nari.ysphd.R;
import com.nari.ysphd.util.inputFilter;
import com.nari.ysphd.view.DropRefreshListView;
import com.nari.ysphd.view.JoinMeetDialog;
import com.nari.ysphd.view.PopDialog;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

@Deprecated
public class MeetingListUI extends BaseActivity implements OnClickListener {
    private static final String TAG = MeetingListUI.class.getSimpleName();
    // 1：未开始
    private List<Meeting> meetingList1;
    // 2：正在进行
    private List<Meeting> meetingList2;
    // 3：已结束
    private List<Meeting> meetingList3;
    private AllAdpter adpter;
    private DropRefreshListView listView;
    private EditText et_search;
    private ImageView iv_message;
    private ImageView iv_menu;
    private View tv_search, back, meetingmanage, message;
    private TextView login_user;
    private ImageView iv_news;
    private ProgressDialog progressDialog;
    private WindowManager wm;
    private String pauseFlag = "0";
    private Integer Num = 1;
    private boolean toNext1 = true;
    private boolean toNext2 = true;
    private boolean toNext3 = true;
    //球机是否存在标志位
    public String CAMERA_EXIST = "0";
    private boolean isFirst = false;
    private TextView meetingback, meetingnext, meetingnum;
    public final String PTZ_EXIST_EVENT = "com.nitc.camera.query";
    public final String CAMERA_EXIST_EVENT = "com.nitc.camera.result";
    private String multiFlag = "0"; //二级互动flag 判定，0 为本地进入 1 为网省访问
    private PopDialog qualityPopDialog;
    private AlertDialog dialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        resetTime();
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_meetinglist);
    }

    @Override
    protected void onDestroy() {
//        remove();
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getMeetingList(Num);
        isFirst = true;
//        resetTime();
        EventBus.getDefault().register(this);
    }

    public void onEventMainThread(SendMessageEvent event) {
        Log.d(TAG, "SendMessageEvent:" + event);
        showSuccessWithStatus("有新的互动邀请");
        if (YCHSInstance.getInstance().getSendMessages().size() > 0) {
            iv_news.setVisibility(View.VISIBLE);
        } else {
            iv_news.setVisibility(View.GONE);
        }
        getMeetingList(1);
        meetingnum.setText("第1页");
    }

    public void onEventMainThread(RefreshEvent event) {
        Log.d(TAG, "RefreshEvent:" + event);
        getMeetingList(1);
        meetingnum.setText("第1页");
    }

    @Override
    protected void initViews() {
        listView = (DropRefreshListView) findViewById(R.id.listView);
        et_search = (EditText) findViewById(R.id.et_search);
        tv_search = (View) findViewById(R.id.tv_search);
        iv_message = (ImageView) findViewById(R.id.iv_message);
        iv_news = (ImageView) findViewById(R.id.iv_news);
        iv_menu = (ImageView) findViewById(R.id.iv_menu);
        back = (View) findViewById(R.id.meetinglist_back);
        message = (View) findViewById(R.id.meetnglist_message);
        meetingmanage = (View) findViewById(R.id.meetnglist_meetingmanage);

        meetingback = (TextView) findViewById(R.id.meetingback);
        meetingnext = (TextView) findViewById(R.id.meetingnext);
        meetingnum = (TextView) findViewById(R.id.meetingnum);

        listView.setDropEnable(new DropRefreshListView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // TODO Auto-generated method stub
                getMeetingList(Num);
            }
        });
    }

    @Override
    public void onBackPressed() {
    }

    @Override
    protected void initData() {
        meetingList1 = new ArrayList<Meeting>();
        meetingList2 = new ArrayList<Meeting>();
        meetingList3 = new ArrayList<Meeting>();
        adpter = new AllAdpter(meetingList2, meetingList1, meetingList3);
        listView.setAdapter(adpter);
        for (int i = 0; i < 3; i++) {
            listView.expandGroup(i);
        }
        if (YCHSInstance.getInstance().getSendMessages().size() > 0) {
            iv_news.setVisibility(View.VISIBLE);
        } else {
            iv_news.setVisibility(View.GONE);
        }
        getMeetingList(Num);
    }

    private void dismissDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    @Override
    protected void initListeners() {
        iv_message.setOnClickListener(this);
        iv_menu.setOnClickListener(this);
        back.setOnClickListener(this);
        message.setOnClickListener(this);
        meetingmanage.setOnClickListener(this);

        meetingback.setOnClickListener(this);
        meetingnext.setOnClickListener(this);

        findViewById(R.id.iv_meetingmanage).setOnClickListener(this);
        et_search.setFilters(new InputFilter[]{new inputFilter(MeetingListUI.this, et_search, 3)});
        et_search.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                et_search.setFocusableInTouchMode(true);
                tv_search.setVisibility(View.GONE);
                return false;
            }
        });
        et_search.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence charsequence, int i, int j, int k) {
            }

            @Override
            public void beforeTextChanged(CharSequence charsequence, int i, int j, int k) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                String filterStr = et_search.getText().toString().trim();
                if (TextUtils.isEmpty(filterStr)) {
                    adpter.resetData(meetingList2, meetingList1, meetingList3);
                    return;
                }
                List<Meeting> filterList1 = new ArrayList<Meeting>();
                for (Meeting meeting1 : meetingList1) {
                    if (meeting1.getMeetingName().contains(filterStr) || meeting1.getHostName().contains(filterStr)) {
                        filterList1.add(meeting1);
                    }
                }
                List<Meeting> filterList2 = new ArrayList<Meeting>();
                for (Meeting meeting2 : meetingList2) {
                    if (meeting2.getMeetingName().contains(filterStr) || meeting2.getHostName().contains(filterStr)) {
                        filterList2.add(meeting2);
                    }
                }
                List<Meeting> filterList3 = new ArrayList<Meeting>();
                for (Meeting meeting3 : meetingList3) {
                    if (meeting3.getMeetingName().contains(filterStr) || meeting3.getHostName().contains(filterStr)) {
                        filterList3.add(meeting3);
                    }
                }
                adpter.resetData(filterList2, filterList1, filterList3);
            }
        });
    }

    JoinMeetDialog joinMeetDialog;
    // 为弹出窗口实现监听类
    private OnClickListener itemsOnClick = new OnClickListener() {
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_joinhome:// 弹框点击加入互动室
                    final String invite_code = joinMeetDialog.getInvite_code_input().getText().toString();
                    joinMeetDialog.dismiss();

                    if (TextUtils.isEmpty(invite_code)) {
                        Toast.makeText(MeetingListUI.this, "请输入密码", Toast.LENGTH_SHORT).show();
                        joinMeetDialog.getInvite_code_input().requestFocus();
                        return;
                    }
                    progressDialog = ProgressDialog.show(MeetingListUI.this, null, "正在处理...");

                    final Meeting meeting = (Meeting) joinMeetDialog.getObject();
                    //20180202 进入互动之前强制退出连接
                      forceLeave(invite_code);
//                    joinMeeting(invite_code);
                    break;
            }
        }

    };

    private void forceLeave(final String invite_code) {
        YCHSConferenceClient.getInstance().leave(new ActionCallback<Void>() {
            @Override
            public void onFailure(WoogeenException arg0) {
                joinMeeting(invite_code);

            }

            @Override
            public void onSuccess(Void arg0) {
                joinMeeting(invite_code);
            }
        });
    }

    /**
     * 加入互动
     *
     * @param invite_code
     */
    private void joinMeeting(final String invite_code) {
        final Meeting meeting = (Meeting) joinMeetDialog.getObject();
        YCHShttpAPI.remoteSignIn(MeetingListUI.this, meeting.getMeetingId(), new StringCallback() {

            @Override
            public void onError(Call call, int statusCode, Exception e) {
                ToastUtil.showToast("加入互动 ：" + e.getMessage());
                Logger.e("joinMeeting " + e.getMessage());
                dismissDialog();
            }

            @Override
            public void onResponse(String response) {
                OnResponse onResponse = YCHShttpAPI.getOnResponse(response);
                if ("0".equals(onResponse.getResultCode())) {
                    if ("false".equals(onResponse.getFlag())) {
                        Logger.e("一级互动: " + (AppConstants.REQUEST_MODE + ConfigUtil.getInstance().getRemoteUrl() + ":" + ConfigUtil.getInstance().getRemotePort()));
                        AppConstants.SERVER_URL = AppConstants.REQUEST_MODE + ConfigUtil.getInstance().getRemoteUrl() + ":" + ConfigUtil.getInstance().getRemotePort();
                        AppConstants.isLocalMeeting = true;
                        multiFlag = "0";
                    } else {
                        String port =  AppConstants.isHttps ? ConfigUtil.getInstance().getAppServerHttpsPort(): ConfigUtil.getInstance().getAppServerHttpPort();
                        Logger.e("二级互动:  " + AppConstants.REQUEST_MODE + ConfigUtil.getInstance().getAgentServer() + ":" + port);
                        AppConstants.SERVER_URL = AppConstants.REQUEST_MODE + ConfigUtil.getInstance().getAgentServer() + ":" + port;
                        // AppConstants.SERVER_URL = AppConstants.HTTP + ConfigUtil.getApp().getRemoteUrl()+":"+ConfigUtil.getApp().getAppServerHttpPort();
                        multiFlag = "1";
                        if ("1".equals(AppConstants.meetingResoure)) {
                            AppConstants.isLocalMeeting = false;
                        }
                    }
                } else {
                    ToastUtil.showToast("加入互动： " + onResponse.getErrorMessage());
                    dismissDialog();
                    return;
                }
                checkJoinMeeting(meeting, invite_code);
            }
        });
    }

    /**
     * 对互动的相关参数进行赋值
     *
     * @param meeting
     * @param invite_code
     */
    private void checkJoinMeeting(final Meeting meeting, String invite_code) {
        String url = "";
        if (AppConstants.isLocalMeeting) {
            url = ConfigUtil.getInstance().getLocalSocketUrl();
        } else {
            url = ConfigUtil.getInstance().getRemoteSocketUrl();
        }
        YCHShttpAPI.CheckJoinMeeting(MeetingListUI.this, url, meeting.getMeetingId(), invite_code, multiFlag, new StringCallback() {
            @Override
            public void onResponse(String response) {
                dismissDialog();
                OnResponse onResponse = YCHShttpAPI.getOnResponse(response);
                if ("0".equals(onResponse.getResultCode())) {
                    joinMeetDialog.dismiss();
                    Logger.e("视频编码格式 :" + onResponse.getCompressType());
                    ConfigUtil.getInstance().setCompressType(onResponse.getCompressType()); //存储编码视频格式
                    ConfigUtil.getInstance().setLocalPort(onResponse.getLocal_port3(), onResponse.getLocal_port4());
                    Logger.e("port3 =" + onResponse.getLocal_port3() + " port4 =" + onResponse.getLocal_port4());
                    ConfigUtil.getInstance().setMcuServerIP(onResponse.getMcuServerIp());
                    //  AppConstants.turnAddrTCP = "turn:" + ConfigUtil.getApp().getMcuServerIP() + ":" + ConfigUtil.getApp().getLocalPort3() + "?transport=tcp";
                    AppConstants.turnAddrTCP = "turn:" + ConfigUtil.getInstance().getAgentServer() + ":" + ConfigUtil.getInstance().getLocalPort3() + "?transport=tcp";
                    Logger.e("turnAddrTCP :" + AppConstants.turnAddrTCP);

                    Intent intent = new Intent(MeetingListUI.this, ConferenceRoomUI.class);
                    intent.putExtra(ConferenceRoomUI.MCU_ROOMID, onResponse.getMcu_room_id());
                    intent.putExtra(ConferenceRoomUI.MEETING_ID, meeting.getMeetingId());
                    intent.putExtra(ConferenceRoomUI.MEETING_NAME, meeting.getMeetingName());
                    intent.putExtra(ConferenceRoomUI.MEETING_SART_TIME, meeting.getStartTime());
                    intent.putExtra(ConferenceRoomUI.MCU_ROLE, onResponse.getRole());
                    intent.putExtra("flag", "1");
                    startActivity(intent);
                } else {
                    ToastUtil.showToast(onResponse.getErrorMessage());
                    Logger.e("chekcJoinMeeting ：" + onResponse.getErrorMessage());
                }
            }

            @Override
            public void onError(Call call, int statusCode, Exception e) {
                ToastUtil.showToast(e.getMessage());
                dismissDialog();
            }
        });

    }

    /**
     * 获取互动列表信息
     *
     * @param Num
     */
    protected void getMeetingList(final Integer Num) {
        YCHShttpAPI.GetMeetingList(MeetingListUI.this, "0", String.valueOf(Num), new StringCallback() {
            @Override
            public void onResponse(String response) {
                listView.onRefreshComplete();
                dismissDialog();
                OnResponse onResponse = YCHShttpAPI.getOnResponse(response);
                Logger.d("getMeetingList 即将开始的互动 " + response);
                meetingList1.clear();
                if ("0".equals(onResponse.getResultCode())) {
                    List<Meeting> meetingList = onResponse.getMeetingList();
                    meetingList1.addAll(meetingList);
                    adpter.notifyDataSetChanged();
                    toNext2 = true;
                } else if ("1".equalsIgnoreCase(onResponse.getResultCode())) {
                    adpter.notifyDataSetChanged();
                    toNext1 = false;
                } else {
                    ToastUtil.showToast(onResponse.getErrorMessage());
                }
            }

            @Override
            public void onError(Call call, int statusCode, Exception e) {
                listView.onRefreshComplete();
                dismissDialog();
            }
        });

        YCHShttpAPI.GetMeetingList(MeetingListUI.this, "1", String.valueOf(Num), new StringCallback() {
            @Override
            public void onResponse(String response) {
                listView.onRefreshComplete();
                dismissDialog();
                OnResponse onResponse = YCHShttpAPI.getOnResponse(response);
                Logger.d("getMeetingList 已经结束的互动 " + response);
                meetingList3.clear();
                if ("0".equals(onResponse.getResultCode())) {
                    List<Meeting> meetingList = onResponse.getMeetingList();
                    meetingList3.addAll(meetingList);
                    adpter.notifyDataSetChanged();
                    toNext3 = true;
                } else if ("1".equalsIgnoreCase(onResponse.getResultCode())) {
                    adpter.notifyDataSetChanged();
                    toNext3 = false;
                } else {
                    ToastUtil.showToast(onResponse.getErrorMessage());
                }
            }

            @Override
            public void onError(Call call, int statusCode, Exception e) {
                listView.onRefreshComplete();
                dismissDialog();
            }
        });

        YCHShttpAPI.GetMeetingList(MeetingListUI.this, "2", String.valueOf(Num), new StringCallback() {
            @Override
            public void onResponse(String response) {
                listView.onRefreshComplete();
                dismissDialog();
                OnResponse onResponse = YCHShttpAPI.getOnResponse(response);
                Logger.d("getMeetingList 正在开始的互动 " + response);
                if ("0".equals(onResponse.getResultCode())) {
                    meetingList2.clear();
                    List<Meeting> meetingList = onResponse.getMeetingList();
                    meetingList2.addAll(meetingList);
                    adpter.notifyDataSetChanged();
                    toNext2 = true;
                } else if ("1".equalsIgnoreCase(onResponse.getResultCode())) {
                    adpter.notifyDataSetChanged();
                    toNext2 = false;
                } else {
                    ToastUtil.showToast(onResponse.getErrorMessage());
                }
            }

            @Override
            public void onError(Call call, int statusCode, Exception e) {
                listView.onRefreshComplete();
                dismissDialog();
            }
        });
    }


    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.iv_message:
                startActivity(new Intent(MeetingListUI.this, UserActivity.class));
                finish();
                break;
            case R.id.iv_menu:
                LogoutDialog();
                break;

            case R.id.iv_meetingmanage:
                Intent intent = new Intent(MeetingListUI.this, MeetingManageUI.class);
                startActivity(intent);
                break;

            case R.id.meetinglist_back:
                LogoutDialog();
                break;
            case R.id.meetnglist_meetingmanage:
                Intent intent2 = new Intent(MeetingListUI.this, MeetingManageUI.class);
                startActivity(intent2);
                break;
            case R.id.meetnglist_message:
                startActivity(new Intent(MeetingListUI.this, UserActivity.class));
                finish();
                break;

            case R.id.meetingback:
                if (Num > 1) {
                    Num--;
                    meetingnext.setClickable(true);
                    meetingnum.setText("第" + Num + "页");
                    getMeetingList(Num);
                } else if (Num == 1) {
                    meetingnext.setClickable(true);
                    meetingnum.setText("第" + Num + "页");
                    getMeetingList(Num);
                    showErrorWithStatus("请往后页查看,前面无数据");
                }
                break;

            case R.id.meetingnext:
                if (!toNext1 && !toNext2) {
                    showErrorWithStatus("请往前页查看,后面无数据");
                    return;
                }
                Num++;
                meetingnum.setText("第" + Num + "页");
                getMeetingList(Num);
                break;

            default:
                break;
        }
    }

    private void Logout() {
//        YCHSWebSocketAPI.getApp().closeSocket();
        YCHSInstance.resetInstance();
        YCHShttpAPI.LogOut(MeetingListUI.this,
                new StringCallback() {
                    @Override
                    public void onResponse(String response) {
//                        if (Platform.getCurrent() != null){
//                            Platform.getCurrent().logout(MeetingListUI.this.getApplicationContext());
//                        }
                        Intent intent = new Intent(MeetingListUI.this, LoginUI.class);
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    public void onError(Call call, int statusCode, Exception e) {
                        finish();
                    }
                });

    }

    private void LogoutDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MeetingListUI.this);
        builder.setMessage("是否要退出登录？");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Logout();
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();

    }


    public class AllAdpter extends BaseExpandableListAdapter {

        private Context context;
        //正在进行
        private List<Meeting> meetingList2;
        //即将开始
        private List<Meeting> meetingList1;
        // 3：已结束
        private List<Meeting> meetingList3;

        public AllAdpter(List<Meeting> meetingList2, List<Meeting> meetingList1, List<Meeting> meetingList3) {
            this.meetingList2 = meetingList2;
            this.meetingList1 = meetingList1;
            this.meetingList3 = meetingList3;
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            switch (groupPosition) {
                case 0:
                    return meetingList2.get(childPosition);
                case 1:
                    return meetingList1.get(childPosition);
                case 2:
                    return meetingList3.get(childPosition);
                default:
                    break;
            }
            return null;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public View getChildView(int groupPosition, final int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {

            if (convertView == null) {
                convertView = LayoutInflater.from(MeetingListUI.this).inflate(
                        R.layout.item_meetlist_child, null);
            }
            final LinearLayout ll_content = (LinearLayout) convertView
                    .findViewById(R.id.ll_content);
            ll_content.setVisibility(View.GONE);
            convertView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (ll_content.getVisibility() == View.VISIBLE) {
                        ll_content.setVisibility(View.GONE);
                    } else {
                        ll_content.setVisibility(View.VISIBLE);
                    }

                }
            });

            final Meeting meeting = (Meeting) getChild(groupPosition, childPosition);
            final TextView room_name = (TextView) convertView.findViewById(R.id.room_name);
            TextView room_mainmember = (TextView) convertView.findViewById(R.id.room_mainmember);
            TextView room_date = (TextView) convertView.findViewById(R.id.room_date);
            TextView room_summary = (TextView) convertView.findViewById(R.id.room_summary);
            TextView room_number = (TextView) convertView.findViewById(R.id.room_number);
            LinearLayout ll_control = (LinearLayout) convertView.findViewById(R.id.ll_control);
            room_name.setText(meeting.getMeetingName());
            room_mainmember.setText(meeting.getHostName());
            room_date.setText(meeting.getStartTime() + " ~ " + meeting.getEndTime());
            room_summary.setText(meeting.getAgenda());
            room_number.setText("互动议程（参会人数:" + meeting.getCurrentNumbers() + "）");
            final Button btn_join = (Button) convertView.findViewById(R.id.join_button);
            Button btn_del = (Button) convertView.findViewById(R.id.delete_button);
            final Button btn_pause = (Button) convertView.findViewById(R.id.pause_button);
            btn_join.setVisibility(View.GONE);
            btn_del.setVisibility(View.GONE);
            btn_pause.setVisibility(View.GONE);
            switch (groupPosition) {
                case 0:
                    ll_control.setVisibility(View.VISIBLE);
                    btn_join.setVisibility(View.VISIBLE);
                    btn_join.setText("加入互动");
                    if (!isMeetingHost(meeting) && "4".equals(meeting.getStatus())) {
                        room_name.setText(meeting.getMeetingName() + "(已暂停)");
                    }
                    btn_join.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (joinMeetDialog != null && joinMeetDialog.isShowing()) {
                                return;
                            } else {
                                joinMeetDialog = new JoinMeetDialog(MeetingListUI.this, itemsOnClick);
                                joinMeetDialog.setObject(meeting);
                                if ("2".equals(meeting.getDataSource()) && ConfigUtil.getInstance().getMeeting_resource().equals("1")) {
                                    ConfigUtil.getInstance().setTurnPort(ConfigUtil.getInstance().getMCUPort3());
                                    ConfigUtil.getInstance().setMCUPort(ConfigUtil.getInstance().getAgentServer());
                                    AppConstants.turnAddrTCP = "turn:" + ConfigUtil.getInstance().getAgentServer() + ":" + ConfigUtil.getInstance().getTurnPort() + "?transport=tcp";
                                } else {
                                    ConfigUtil.getInstance().setMCUPort(ConfigUtil.getInstance().getLocalPort4());
                                    ConfigUtil.getInstance().setTurnPort(ConfigUtil.getInstance().getLocalPort3());
                                    AppConstants.turnAddrTCP = "turn:" + ConfigUtil.getInstance().getRemoteUrl() + ":" + ConfigUtil.getInstance().getTurnPort() + "?transport=tcp";
                                }
                                //查询是不是被邀请的用户
                                Map<String, String> params = new HashMap<>();
                                params.put("meetingId", meeting.getMeetingId());

                                if ("1".equals(meeting.getJoinStatus())) {
                                    //remoteSignIn(meeting, meeting.getInvite_code());
                                    forceLeave(meeting.getInvite_code());
                                } else {
                                    joinMeetDialog.showAtLocation(ll_content, Gravity.CENTER, 0, 0);
                                }
                            }
                        }
                    });
                    //add 2017/11/23
                    //在正在开始的互动并且是主持人的时候显示
                    if (isMeetingHost(meeting)) {
                        btn_pause.setVisibility(View.VISIBLE);
                        switch (meeting.getStatus()) {
                            case "4"://互动暂停
                                btn_pause.setText("取消暂停");
                                btn_join.setVisibility(View.GONE);
                                pauseFlag = "1";
                                break;
                            case "2"://互动进行中
                                btn_pause.setText("暂停互动");
                                pauseFlag = "0";
                                break;
                        }
                        //并且互动室人数为0
                        btn_pause.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if ("0".equals(pauseFlag)) {
                                    if ("0".equals(meeting.getCurrentNumbers())) {
                                        pauseMeeting(btn_pause,pauseFlag, meeting.getMeetingId());
                                        btn_join.setVisibility(View.GONE);
                                    } else {
                                        Toast.makeText(MeetingListUI.this, "当前互动有人，无法暂停", Toast.LENGTH_LONG).show();
                                    }

                                }
                                if ("1".equals(pauseFlag)) {
                                    pauseMeeting(btn_pause,pauseFlag, meeting.getMeetingId());
                                    btn_join.setVisibility(View.VISIBLE);
                                }

                            }
                        });
                    }
                    break;
                case 1:
                    ll_control.setVisibility(View.VISIBLE);
                    btn_join.setVisibility(View.VISIBLE);
                    btn_del.setVisibility(View.VISIBLE);
                    btn_join.setText("编辑");
                    btn_join.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!"1".equals(meeting.getStatus())) {
                                showErrorWithStatus("只能编辑未开始的互动");
                                return;
                            }
                            Intent intent = new Intent(MeetingListUI.this, MeetingManageUI.class);
                            intent.putExtra(MeetingManageUI.BUNDLE_MEETING_ID, meeting.getMeetingId());
                            startActivity(intent);
                        }
                    });
                    btn_del.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            prompt2Dialog("确定删除" + meeting.getMeetingName()
                                    + "这个互动吗？", new PromptListener() {

                                @Override
                                public void callBack() {
                                    // TODO Auto-generated method stub
                                    progressDialog = ProgressDialog.show(MeetingListUI.this, null, "正在删除...");
                                    YCHShttpAPI.deleteMeeting(MeetingListUI.this, meeting.getMeetingId(), new StringCallback() {

                                        @Override
                                        public void onResponse(String response) {
                                            // TODO Auto-generated method stub
                                            if (progressDialog != null && progressDialog.isShowing()) {
                                                progressDialog.dismiss();
                                            }
                                            OnResponse onResponse = YCHShttpAPI.getOnResponse(response);
                                            if ("0".equals(onResponse.getResultCode())) {
                                                if (meetingList1 != null && meetingList1.contains(meeting)) {
                                                    Toast.makeText(MeetingListUI.this, "删除成功！", Toast.LENGTH_SHORT).show();
                                                    meetingList1.remove(meeting);
                                                    adpter.notifyDataSetChanged();
                                                }
                                            } else {
                                                if (TextUtils.isEmpty(onResponse.getErrorMessage())) {
                                                    Toast.makeText(MeetingListUI.this, "删除出错请重试", Toast.LENGTH_SHORT).show();
                                                } else {
                                                    Toast.makeText(MeetingListUI.this, onResponse.getErrorMessage(), Toast.LENGTH_SHORT).show();
                                                }
                                            }
                                        }

                                        @Override
                                        public void onError(Call call, int statusCode, Exception e) {
                                            // TODO Auto-generated method stub
                                            if (progressDialog != null && progressDialog.isShowing()) {
                                                progressDialog.dismiss();
                                            }
                                            System.out.println("onError:" + call + " statusCode:" + statusCode);
                                            Toast.makeText(MeetingListUI.this, "删除出错请重试", Toast.LENGTH_SHORT).show();
                                            e.printStackTrace();
                                        }
                                    });
                                }
                            });
                        }
                    });
                    break;
                case 2:
                    ll_control.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
            return convertView;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            switch (groupPosition) {
                case 0:
                    return meetingList2.size();
                case 1:
                    return meetingList1.size();
                case 2:
                    return meetingList3.size();
                default:
                    break;
            }
            return 0;
        }

        @Override
        public Object getGroup(int groupPosition) {
            // return father.get(groupPosition);
            return null;
        }

        @Override
        public int getGroupCount() {
            return 3;
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public View getGroupView(int groupPosition, final boolean isExpanded, View convertView, ViewGroup parent) {
            View view = LayoutInflater.from(MeetingListUI.this).inflate(R.layout.item_meetlist_farter, null);
            ImageView iv_type = (ImageView) view.findViewById(R.id.iv_type);
            TextView tv_type = (TextView) view.findViewById(R.id.tv_type);
            ImageView iv_jiantou = (ImageView) view.findViewById(R.id.iv_jiantou);
            if (groupPosition == 0) {
                tv_type.setText("正在进行");
                iv_type.setImageResource(R.drawable.conduct);
            } else if (groupPosition == 1) {
                tv_type.setText("即将开始");
                iv_type.setImageResource(R.drawable.begin);
            } else {
                tv_type.setText("历史互动");
            }
            iv_jiantou.setImageResource(R.drawable.down);
            if (!isExpanded) {
                iv_jiantou.setImageResource(R.drawable.up);
            }
            return view;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {

            return true;

        }

        public void resetData(List<Meeting> list2, List<Meeting> list1, List<Meeting> list3) {
            this.meetingList2 = list2;
            this.meetingList1 = list1;
            this.meetingList3 = list3;
            notifyDataSetChanged();
        }

    }

    private void pauseMeeting(final Button btn_pause, String pauseFlag1, String meetingId) {
        Map<String, String> params = new HashMap<>();
        params.put("flag", pauseFlag1);
        params.put("meetingId", meetingId);
        YCHShttpAPI.PauseMeeting(MeetingListUI.this, params, new StringCallback() {
            @Override
            public void onError(Call call, int statusCode, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                OnResponse resp = YCHShttpAPI.getOnResponse(response);
                if ("0".equals(resp.getResultCode())) {
                    if ("4".equals(resp.getStatus())) {// 4 暂停的互动
                        Toast.makeText(MeetingListUI.this, "互动已暂停!", Toast.LENGTH_SHORT).show();
                        pauseFlag = "1";
                        btn_pause.setText("取消暂停");
                    } else if ("2".equals(resp.getStatus())){
                        btn_pause.setText("暂停互动");
                        pauseFlag = "0";
                        Toast.makeText(MeetingListUI.this, "互动已取消暂停！", Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(MeetingListUI.this, String.valueOf(resp.getMessage()),Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    //判断是不是互动主持人
    private boolean isMeetingHost(Meeting meeting) {
        return meeting.getHostCode().equals(ConfigUtil.getInstance().getLoginUser().getUSER_CODE());
    }

    private InputFilter inputFilter = new InputFilter() {
        Pattern pattern = Pattern.compile("[^a-zA-Z0-9\\u4E00-\\u9FA5_,.?!:;…~_\\-\"\"/@*+'()<>{}/[/]()<>{}\\[\\]=%&$|\\/♀♂#¥£¢€\"^` ，。？！：；……～" +
                "“”、“（）”、（——）‘’@‘·’＆＊＃《》￥《〈〉》〈＄〉［］￡［］｛｝｛｝￠【】【】％〖〗〖〗／〔〕〔〕＼『』『』＾「」「」｜﹁﹂｀．]");
        Pattern pattern2 = Pattern.compile("[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？§№☆★○●◎◇◇◆□△▲■※＃→←↑-]");

        @Override
        public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
            Matcher matcher = pattern.matcher(charSequence);
            Matcher matcher1 = pattern2.matcher(charSequence);
            if (!matcher.find()) {
                if (matcher1.find()) {
                    et_search.setError(Comm.getPrompt("请规范输入搜索关键字"));
                    Toast.makeText(MeetingListUI.this, "非法字符！", Toast.LENGTH_SHORT).show();
                    return "";
                }
                if (charSequence.equals(" ")) {
                    et_search.setError(Comm.getPrompt("请规范输入搜索关键字"));
                    Toast.makeText(MeetingListUI.this, "非法字符！", Toast.LENGTH_SHORT).show();
                    return "";
                }
                return null;
            } else {
                et_search.setError(Comm.getPrompt("请规范输入搜索关键字"));
                Toast.makeText(MeetingListUI.this, "非法字符！", Toast.LENGTH_SHORT).show();
                return "";
            }
        }
    };

    private InputFilter inputFilter2 = new InputFilter() {

        @Override
        public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
            if (charSequence.equals(" ")) {
                et_search.setError(Comm.getPrompt("请规范输入搜索关键字"));
                Toast.makeText(MeetingListUI.this, "非法字符！", Toast.LENGTH_SHORT).show();
                return "";
            } else {
                return null;

            }
        }
    };
}
